<template>
  <div class="page-demand">
    <!-- 顶部导航 -->
    <div class="flex items-center justify-between h-16 bg-white border-b border-gray-200">
      <div class="flex items-center space-x-4">
        <el-icon class="text-orange-500 cursor-pointer text-xl" @click="back" style="color: #409eff; font-weight: bold; font-size: 26px;">
          <ArrowLeft />
        </el-icon>
        <span class="text-gray-700 font-color" style="font-size: 22px;">{{ formData.enterpriseName }}</span>
        <span class="text-gray-500 ml-8 font-color" style="font-size: 22px;">{{ formData.demandCode }}</span>
      </div>

      <div class="flex items-center space-x-4">
        <span class="text-gray-600" style="font-size: 22px;">审核人：{{ formData.approver || '--' }}</span>
        <span class="text-gray-400" style="font-size: 22px;">|</span>
        <span class="text-gray-600" style="font-size: 22px;">申请时间：{{ formData.createTime ? formatTime(formData.createTime) : '--' }}</span>
      </div>
    </div>
    <div class="label bg-color">需求详情</div>


    <div class="bd-dj">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
      >
        <el-row style="width: 100%">
          <el-form-item label="需求名称" prop="demandName" class="custom-label-size">
           <span class="custom-label-size"> {{ formData.demandName || '--' }}</span>
          </el-form-item>
        </el-row>

        <el-row style="width: 100%">
          <el-form-item label="发布时间" prop="demandName" class="custom-label-size">
            <span class="custom-label-size">  {{ formData.createTime ? formatTime(formData.createTime) : '--' }} </span>
          </el-form-item>
        </el-row>

        <el-row style="width: 100%">
          <el-form-item label="需求描述" prop="demandName" class="custom-label-size">
            <span class="custom-label-size">  {{ formData.demandDescription || '--' }} </span>
          </el-form-item>
        </el-row>

        <el-row style="width: 100%">
          <el-form-item label="交易单元" prop="demandDescription" class="custom-label-size">
            <!-- 循环展示单元 -->
            <div v-for="(item, index) in formData.demandInfoTradingUnitMapList" :key="index">
              <span class="custom-label-size">{{ item.tradingUnitName }}-{{ item.tradingUnit }}</span>&nbsp;&nbsp;
            </div>
          </el-form-item>
        </el-row>

        <el-row style="width: 100%; max-height: 170px; overflow-y: auto;">

          <el-form-item
label-width="100px"  prop="demandDescription"
          class="d-form-item custom-label-size"
          v-if="formData.status === '已确认' || formData.status === '已关闭' || formData.status === '已完成'">
            <template #label>
              操作电量<br/>(MWh)
            </template>
            <el-row v-for="(item, index) in formData.demandInfoTradingUnitMapList" :key="index" style="width: 100%;">
              <el-row style="width: 100%;" v-for="(c, index) in item.demandInfoTradingUnitDO" :key="index" >
                <el-col :span="5">
                  <h3 class="custom-label-size" style="display: flex; justify-content: flex-start; flex-wrap: nowrap; align-items: center;">{{ item.tradingUnitName + '—' + item.tradingUnit }}</h3>
                </el-col>
                <el-col :span="3">
                  <h3 class="custom-label-size">转让类型：{{ c.type === '1' ? '转入' : c.type === '2' ? '转出' : '-'}}</h3>
                </el-col>
                <el-col :span="6">
                  <el-row>
                    <h3 class="custom-label-size">峰：{{ c.feng }}</h3>
                    <h3 class="custom-label-size">&nbsp;&nbsp;平：{{ Number(c.ping).toFixed(3) }}</h3>
                    <h3 class="custom-label-size">&nbsp;&nbsp;谷：{{ Number(c.gu).toFixed(3) }}</h3>
                    <h3 class="custom-label-size">&nbsp;&nbsp;总：{{ Number(c.zong).toFixed(3) }}</h3>
                  </el-row>
                </el-col>
                <el-col :span="4">
                  <h3 class="custom-label-size">预计操作日期：{{ c.expectedDate ? c.expectedDate.replace(/T/g, ' ').replace(/\.000Z/g, '') : '' }}</h3>
                </el-col>
                <el-col :span="6">
                  <h3 class="custom-label-size">转让对象：{{
                          c.participateTradingDo ? c.participateTradingDo.tradingUnit : c.notTrading
                        }}</h3>
                </el-col>
              </el-row>

            </el-row>
          </el-form-item>

        </el-row>

      </el-form>
    </div>

    <el-tabs
      v-model="editableTabsValue"
      type="card"
      class="demo-tabs"
      closable
      @tab-remove="removeTab"
      @tab-change="tabChange"
    >
      <el-tab-pane
        v-for="item in unitList"
        :key="item.tradingUnitId"
        :label="item.tradingUnitName+ '——' +item.tradingUnit"
        :name="item.tradingUnitId"
      >
        <!-- 根据不同的 tab 显示不同的组件 -->
        <!--<detailsTable :formType="formType" :tradingUnitId="item.tradingUnitId" :mainId="mainId" :tableList="tableList" :zhuanrangriqiList="zhuanrangriqiList" />-->
        <component :is="detailsTable" :formType="formType" :tradingUnitId="item.tradingUnitId" :mainId="mainId" :tableList="tableList" :zhuanrangriqiList="zhuanrangriqiList" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script setup lang="ts">
import { DemandInfoMainApi } from '@/api/dd/demandinfomain'
import { DemandInfoTradingUnitVO } from '@/api/dd/demandinfotradingunit'
import { ref } from 'vue'
import {TradingUnitApi} from "@/api/dd/tradingunit";
import detailsTable from "@/views/dd/dolog/details-table.vue";
import {usePermissionStore} from "@/store/modules/permission";
import {ArrowLeft} from "@element-plus/icons-vue";
/** 需求信息主 表单 */
defineOptions({ name: 'DialogDoLogInfoMainForm' })

const { t } = useI18n() // 国际化


// 时间戳格式化函数
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day}-${hours}:${minutes}:${seconds}`;
}

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  demandCode: undefined,
  enterpriseId: undefined,
  enterpriseName: undefined,
  demandName: undefined,
  demandDescription: undefined,
  status: undefined,
  notPassing: undefined,
  createTime: undefined
})
const formRules = reactive({
})
const formRef = ref() // 表单 Ref
const mainId = ref(0)

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调


/** 查询需求下的订单 */
//交易单元
const unitList = ref<DemandInfoTradingUnitVO[]>([])

/** 选择交易单元 */
const editableTabsValue: any = ref('')
const editableTabs: any = ref([])

// 表格列表
const tableList = ref([])

// 转让日期
const zhuanrangriqiList = ref([])

// 获取转让日期列表
const getDateList = () => {
  DemandInfoMainApi.getDateListApi({ unitId: editableTabsValue.value, id: mainId.value }).then(res => {
    zhuanrangriqiList.value = res.data.filter(item => item).map(item => {
      return item.replace(/T/g, ' ').replace(/\.000Z/g, '');
    })
  })
}

const tabChange = (tradingUnitId: number) => {
  // console.log(tradingUnitId, `id=${tradingUnitId}`, unitList.value)
  console.log(formData.value, 'formData')
  editableTabsValue.value = tradingUnitId
  //切换是获取当前页面的表格的数据

  nextTick(async () => {
    const canyujiaoyidanyuan = await TradingUnitApi.getTradingUnitSelect()
    tableList.value = (unitList.value as any).filter(item => item.tradingUnitId === tradingUnitId)[0].demandInfoTradingUnitDO.map(item => {
      return {
        ...item,
        radio: item.participateTradingId ? '1' : (item.notTrading ? '2' : '1'),
        canyujiaoyidanyuan,
        change: (val, item) => {
          if (val === '1') {
            item.notTrading = ''
          } else {
            item.participateTradingId = ''
          }
        },
      }
    })
    // getDateList()
    console.log(unitList.value, 'unitList.value')
  })
  // console.log(tableList, 'tableList.value')
}
const removeTab = (id: number) => {
  const tabs  = editableTabs.value
  let activeId = editableTabsValue.value
  if (activeId === id) {
    tabs.forEach((tab, index) => {
      if ((tab as any).id === id) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeId = (nextTab as any).id
        }
      }
    })
  }

  editableTabsValue.value = id
  editableTabs.value = tabs.filter((tab) => (tab as any).id !== id)
}

getDateList()

const permissionStore = usePermissionStore()
/** 打开弹窗 */
const open = async (type: string = formType.value, id: any = formData.value.id) => {
  // dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type

  mainId.value = id

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = permissionStore.getDoLog
      console.log(permissionStore.getDoLog, 'permissionStore.getDoLog')
      console.log(formData.value, 'formData.value')
      unitList.value = (formData.value as any).demandInfoTradingUnitMapList
      // console.log(unitList.value, 'unitList.value')
      editableTabsValue.value = unitList.value[0].tradingUnitId
      tabChange(unitList.value[0].tradingUnitId)
    } finally {
      formLoading.value = false
    }
  }

}

const router = useRouter()
const route = useRoute()

const back = () => {
  router.go(-1)
}

onMounted(() => {
// (orderStatus as any).value = route.query.orderStatus
//   console.log(permissionStore.getDoLog, 'permissionStore.getDoLog')
  open(formType.value, route.query.id)
})
</script>

<style lang="scss" scoped>

.label {
  width: 100px;
  text-align: center;
  padding: 8px;
  color: #fff;
  font-weight: bold;
}

.bg-color {
  background-color: #409eff;
}
.font-color {
  color: #409eff;
}

:deep(.el-tabs__item.is-active), :deep(.el-tabs__item:hover) {
  background-color: #409eff;
  color: #fff;
}

:deep(.el-form-item__label) {
  display: flex;
  justify-content: flex-start;
  color: #409eff;
  white-space: nowrap;
  font-size: 18px;
}

.bd-dj {
  width: 100%;
  padding: 8px 12px;
  box-sizing: border-box;
  border: 1px solid #409eff;
  margin: 20px 0;
}

.page-demand {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  background-color: #fff;
}
.el-tabs__nav-wrap::after {
  height: 1px;
}

.el-input__wrapper,
.el-textarea__wrapper {
  box-shadow: 0 0 0 1px #dcdfe6;
}

.el-input__wrapper:hover,
.el-textarea__wrapper:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.el-input__wrapper.is-focus,
.el-textarea__wrapper.is-focus {
  box-shadow: 0 0 0 1px #409eff;
}
.custom-label-size {
  :deep(.el-form-item__label) {
    font-size: 16px; // 设置字体大小为 8px
  }
}
.d-form-item {
  width: 100%;
}

.el-form-item--default {
  margin-bottom: 0;
  .el-form-item__content {
    height: 26px;
    line-height: 26px;
  }
}

</style>
